package mviewer.types;

public class VectorUtil {

	static public float length(float x, float y, float z) {
		return (float)Math.pow(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2), 0.5);
	}

	static public float length(IVector v) {
		return length(v.getX(), v.getY(), v.getZ());
	}

	static public float scalar(float ax, float ay, float az, float bx, float by, float bz) {
		float xx = ax==0 || bx==0 ? 0 : ax * bx,
			  yy = ay==0 || by==0 ? 0 : ay * by,
			  zz = az==0 || bz==0 ? 0 : az * bz;

		return xx + yy + zz;
	}

	static public float scalar(IVector v0, IVector v1) {
		return scalar(v0.getX(), v0.getY(), v0.getZ(), v1.getX(), v1.getY(), v1.getZ());
	}

	static public void crossProduct(IVector a, IVector b, IWritableVector result) {
		float ax = a.getX(), ay = a.getY(), az = a.getZ(),
			  bx = b.getX(), by = b.getY(), bz = b.getZ(),
			  yz = ay == 0 || bz == 0 ? 0 : ay * bz,
			  zy = az == 0 || by == 0 ? 0 : az * by,
			  zx = az == 0 || bx == 0 ? 0 : az * bx,
			  xz = ax == 0 || bz == 0 ? 0 : ax * bz,
			  xy = ax == 0 || by == 0 ? 0 : ax * by,
			  yx = ay == 0 || bx == 0 ? 0 : ay * bx;

		result.setX(yz - zy);
		result.setY(zx - xz);
		result.setZ(xy - yx);
	}

	static public void add(IVector a, IVector b, IWritableVector result) {
		result.setX(a.getX() + b.getX());
		result.setY(a.getY() + b.getY());
		result.setZ(a.getZ() + b.getZ());
	}

	static public void sub(IVector a, IVector b, IWritableVector result) {
		result.setX(a.getX() - b.getX());
		result.setY(a.getY() - b.getY());
		result.setZ(a.getZ() - b.getZ());
	}

	static public void normalize(IWritableVector vector) {
		normalize(vector, vector);
	}

	static public void normalize(IVector source, IWritableVector result ) {
		float length = VectorUtil.length(source);

		if (length != 0)
			divide(source, length, result);
	}

	static public void divide(IVector source, float divisor, IWritableVector result) {
		if (divisor == 0)
			throw new IllegalArgumentException("divisor cannot be 0");

		float x = source.getX(),
			y = source.getY(),
			z = source.getZ();

		result.setX(x == 0 ? 0 : x / divisor);
		result.setY(y == 0 ? 0 : y / divisor);
		result.setZ(z == 0 ? 0 : z / divisor);
	}
}
